package com.foxzzz.datamemory.service;

import com.foxzzz.datamemory.entity.BookMetaData;
import com.foxzzz.datamemory.entity.BookNote;
import com.foxzzz.datamemory.repository.BookMetaDataRepository;
import com.foxzzz.datamemory.util.SnowflakeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class BookMetaDataService {
    @Autowired
    private BookMetaDataRepository repository;


    public BookMetaData save(BookMetaData bookMetaData) {
        if (bookMetaData.getId() == null) {
            bookMetaData.setId(SnowflakeUtil.getIdString());
            bookMetaData.setDateCreate(new Date());
            if (bookMetaData.getOrders() == 0) {
                bookMetaData.setOrders(bookMetaData.getDateCreate().getTime());
            }
        }
        return repository.save(bookMetaData);
    }

    public void delete(String id) {
        repository.deleteById(id);
    }

    /**
     * 按条件 分页查询bookNote
     *
     * @param bookMetaData
     * @param page
     * @param size
     * @param order
     * @return
     */
    public Page<BookMetaData> page(BookMetaData bookMetaData, int page, int size, String order) {
        Sort by = "asc".equals(order) ? Sort.by(Sort.Order.asc("orders")) : Sort.by(Sort.Order.desc("orders"));
        PageRequest of = PageRequest.of(page, size, by);
        return bookMetaData == null ? repository.findAll(of) : repository.findAll(Example.of(bookMetaData), of);
    }
}
